<script lang="ts" setup>
import { computed, onActivated, ref } from 'vue'
import { useSkusStore } from '@/stores/skus'
import type { IAttrItem, ISkuItem } from '@/stores/types';

interface ISkuDataItem extends ISkuItem {
  // sku 对应的 属性值 id 字符串连接
  valueIdStr: string;
}
interface IAttrFormItem extends IAttrItem {
  // 选中的属性值
  selected: string;
}

// sku
const skuData = ref<ISkuDataItem[]>([])
// 属性
const attrData = ref<IAttrFormItem[]>([])
const init = () => {
  const { attrs, skus } = useSkusStore()
  skuData.value = skus.map((item) => {
    return {
      ...item,
      valueIdStr: item.skuAttrs.map(v => v.valueId).join(),
    }
  })
  attrData.value = attrs.map((item) => {
    return {
      ...item,
      selected: ''
    }
  })
  console.log('所有属性==', attrData.value)
  console.log('所有sku==', skuData.value)
}

// 可选sku
const canSelectSkus = computed(() => {
  return skuData.value.map(it => it.skuAttrs.map(v => v.valueLabel).join('-'))
})

// 选择的属性
const selectedAttrs = ref<string[]>([])
// 属性change
const currentSku = ref({} as ISkuDataItem)

const handleChangeAttr = () => {
  selectedAttrs.value = attrData.value
    .filter(v => v.selected)
    .map(v => v.attrValues.find(i => i.valueId === v.selected)?.valueLabel ?? '')
  const selecteds = attrData.value.map(v => v.selected)
  const selectedIdStr = selecteds.join()
  const targetSku = skuData.value.find(v => v.valueIdStr === selectedIdStr)
  console.log('最终选中的sku===', targetSku)
  currentSku.value = targetSku!
}

const handleComfirm = () => {
  console.log('comfirm sku===', currentSku.value)
}

// 有更新时重新拉取
onActivated(init)
</script>

<template>
  <main>
    <el-card>
      <el-form :model="{ attrData }" label-suffix="：">
        <template v-for="item of attrData" :key="item.skuId">
          <el-form-item :label="item.attrLabel">
            <el-radio-group v-model="item.selected" @change="handleChangeAttr">
              <el-radio
                v-for="it of item.attrValues"
                :key="it.valueId"
                :label="it.valueId"
                border
              >{{ it.valueLabel }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
      </el-form>
      <el-row type="flex" justify="end" class="mt-2">
        <el-button type="success" @click="handleComfirm">确定</el-button>
      </el-row>
      <section>
        <b>可选的sku：</b>
        <el-button
          v-for="it of canSelectSkus"
          :key="it"
          :label="it"
          border
        >{{ it }}</el-button>
      </section>
      <section>
        <b>选中的属性：</b>
        <span>{{ selectedAttrs }}</span>
      </section>
      <section>
        <b>选中的sku：</b>
        <span>{{ currentSku?.skuId }}</span>
        <!-- <pre>{{ currentSku }}</pre> -->
      </section>
    </el-card>
  </main>
</template>
